import {useEffect, useState} from 'react';

type Subscriber = () => void;

export default () => {
  const [selectedProducts, setSelectedProducts] = useState<any[]>(() => {
    const savedProducts = localStorage.getItem('selectedProducts');
    return savedProducts ? JSON.parse(savedProducts) : [];
  });

  const [subscribers] = useState<Set<Subscriber>>(new Set());

  useEffect(() => {
    localStorage.setItem('selectedProducts', JSON.stringify(selectedProducts));
  }, [selectedProducts]);

  const notifySubscribers = () => {
    subscribers.forEach(subscriber => subscriber());
  };

  const subscribe = (callback: Subscriber) => {
    subscribers.add(callback);
    return () => subscribers.delete(callback);
  };

  const addProduct = (product: any) => {
    setSelectedProducts((prevProducts) => {
      const existingProduct = prevProducts.find((p) => p.id === product.id);
      const updatedProducts = existingProduct
        ? prevProducts.map((p) =>
            p.id === product.id ? { ...p, quantity: p.quantity + 1 } : p
          )
        : [...prevProducts, { ...product, quantity: 1 }];
      localStorage.setItem('selectedProducts', JSON.stringify(updatedProducts));
      notifySubscribers();
      return updatedProducts;
    });
  };

  const removeProduct = (productId: string) => {
    setSelectedProducts((prevProducts) => {
      const updatedProducts = prevProducts.filter((p) => p.id !== productId);
      notifySubscribers();
      return updatedProducts;
    });
  };

  const updateProductQuantity = (productId: string, quantity: number) => {
    setSelectedProducts((prevProducts) => {
      const updatedProducts = prevProducts.map((p) =>
        p.id === productId ? { ...p, quantity: Math.max(1, quantity) } : p
      );
      notifySubscribers();
      return updatedProducts;
    });
  };

  const clearSelectedProducts = () => {
    setSelectedProducts([]);
    localStorage.removeItem('selectedProducts');
  };

  return {
    selectedProducts,
    addProduct,
    removeProduct,
    updateProductQuantity,
    clearSelectedProducts,
    subscribe,
  };
};
